<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"vchao.top","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
<meta property="og:type" content="website">
<meta property="og:title" content="乘风破浪">
<meta property="og:url" content="http://vchao.top/page/5/index.html">
<meta property="og:site_name" content="乘风破浪">
<meta property="og:description" content="怀揣好奇，梦想改变世界的菜鸟极客">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="vchao">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://vchao.top/page/5/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>乘风破浪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">乘风破浪</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/12/%E5%8A%A8%E6%80%81%E6%9B%B4%E6%8D%A2%E5%BA%94%E7%94%A8%E5%9B%BE%E6%A0%87%EF%BC%9Aactivity-alias%E8%AF%A6%E8%A7%A3%E5%8F%8A%E5%BA%94%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/12/%E5%8A%A8%E6%80%81%E6%9B%B4%E6%8D%A2%E5%BA%94%E7%94%A8%E5%9B%BE%E6%A0%87%EF%BC%9Aactivity-alias%E8%AF%A6%E8%A7%A3%E5%8F%8A%E5%BA%94%E7%94%A8/" class="post-title-link" itemprop="url">动态更换应用图标：activity-alias详解及应用</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-12 20:03:39" itemprop="dateCreated datePublished" datetime="2017-05-12T20:03:39+08:00">2017-05-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>﻿### 动态更换图标</p>
<p>首先先解决下实际问题。动态更换图标。android可以根据activity-alias来设置桌面可以存在多个icon，那直接通过设置某个activity-alias显示其他隐藏即可实现。下面上代码</p>
<ol>
<li>在xml添加多个activity-alias、删除MainActivity标签的 <code>&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;</code>属性。</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">activity-alias</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:name</span>=<span class="string">&quot;.icon_tag&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:enabled</span>=<span class="string">&quot;true&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:icon</span>=<span class="string">&quot;@mipmap/ic_launcher&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:label</span>=<span class="string">&quot;111111&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:targetActivity</span>=<span class="string">&quot;.MainActivity&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">action</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.action.MAIN&quot;</span> /&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">category</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.category.LAUNCHER&quot;</span> /&gt;</span></span><br><span class="line">          <span class="tag">&lt;/<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">activity-alias</span>&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="tag">&lt;<span class="name">activity-alias</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:name</span>=<span class="string">&quot;.icon_tag_1212&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:enabled</span>=<span class="string">&quot;false&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:icon</span>=<span class="string">&quot;@mipmap/head&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:label</span>=<span class="string">&quot;222222&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">android:targetActivity</span>=<span class="string">&quot;.MainActivity&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">action</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.action.MAIN&quot;</span> /&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">category</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.category.LAUNCHER&quot;</span> /&gt;</span></span><br><span class="line">          <span class="tag">&lt;/<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">activity-alias</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>如上图 指向的targetActivity可以是不同的，这样启动的activity也是不是一样的，主要的是name要和代码中保持一致</p>
<p>2、代码中控制活动和普通图标的切换</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> useCode =1、为活动图标 =2 为用普通图标 =3、不启用判断</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">switchIcon</span><span class="params">(<span class="keyword">int</span> useCode)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//要跟manifest的activity-alias 的name保持一致</span></span><br><span class="line">           String icon_tag = <span class="string">&quot;top.vchao.icon.icon_tag&quot;</span>;</span><br><span class="line">           String icon_tag_1212 = <span class="string">&quot;top.vchao.icon.icon_tag_1212&quot;</span>;</span><br><span class="line"></span><br><span class="line">           <span class="keyword">if</span> (useCode != <span class="number">3</span>) &#123;</span><br><span class="line"></span><br><span class="line">               PackageManager pm = getPackageManager();</span><br><span class="line"></span><br><span class="line">               ComponentName normalComponentName = <span class="keyword">new</span> ComponentName(</span><br><span class="line">                       getBaseContext(),</span><br><span class="line">                       icon_tag);</span><br><span class="line">               <span class="comment">//正常图标新状态</span></span><br><span class="line">               <span class="keyword">int</span> normalNewState = useCode == <span class="number">2</span> ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED</span><br><span class="line">                       : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;</span><br><span class="line">               <span class="keyword">if</span> (pm.getComponentEnabledSetting(normalComponentName) != normalNewState) &#123;<span class="comment">//新状态跟当前状态不一样才执行</span></span><br><span class="line">                   pm.setComponentEnabledSetting(</span><br><span class="line">                           normalComponentName,</span><br><span class="line">                           normalNewState,</span><br><span class="line">                           PackageManager.DONT_KILL_APP);</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               ComponentName actComponentName = <span class="keyword">new</span> ComponentName(</span><br><span class="line">                       getBaseContext(),</span><br><span class="line">                       icon_tag_1212);</span><br><span class="line">               <span class="comment">//正常图标新状态</span></span><br><span class="line">               <span class="keyword">int</span> actNewState = useCode == <span class="number">1</span> ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED</span><br><span class="line">                       : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;</span><br><span class="line">               <span class="keyword">if</span> (pm.getComponentEnabledSetting(actComponentName) != actNewState) &#123;<span class="comment">//新状态跟当前状态不一样才执行</span></span><br><span class="line"></span><br><span class="line">                   pm.setComponentEnabledSetting(</span><br><span class="line">                           actComponentName,</span><br><span class="line">                           actNewState,</span><br><span class="line">                           PackageManager.DONT_KILL_APP);</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>上图的icon_tag和icon_tag_1212要和你xml中的activity-alias的name保持一致</p>
<p>补坑。。<strong>activity-alias的name是不能改的!!</strong><br>如果当前版本的是icon_tag_1212，下版本改成icon_tag_act，就会导致系统找icon_tag_1212找不到，导致桌面无图标，应用打不开！！！此坑严重请注意</p>
<h3 id="activity-alias标签元素"><a href="#activity-alias标签元素" class="headerlink" title="activity-alias标签元素"></a>activity-alias标签元素</h3><p>实现了功能，下面就来看一下原理。所周知，AndroidManifest是一个xml文件，它包含很多标签元素，如application、activity、receiver等，其中有一个叫做activity-alias，因为该标签平时很少用到，可能大家对这个标签还不是很熟悉。</p>
<p>activity-alias，顾名思义，即activity的别名。看到这里，大家会想那它究竟是哪个Activity的别名呢？我们在创建一个Activity时，必须在AndroidManifest中静态声明该Activity，同时配置android:name、android:label、android:icon等属性，还可配置intent-filter。对于activity-alias标签，它有一个属性叫android:targetActivity，这个属性就是用来为该标签设置目标Activity的，或者说它就是这个目标Activity的别名。至此我们已经明白activity-alias并非代表一个独立的Activity，而是为一个已经存在的Activity创建的别名。</p>
<h3 id="activity-alias功能"><a href="#activity-alias功能" class="headerlink" title="activity-alias功能"></a>activity-alias功能</h3><p>知道了activity-alias的概念，那么它的功能是什么呢？activity-alias作为一个已存在Activity的别名，则应该可以通过该别名标签声明快速打开目标Activity。因此activity-alias可用来设置某个Activity的快捷入口，可以放在桌面上或者通过该别名被其他组件快速调起。该标签元素支持一些属性及intent-filter、meta-data等配置，因此可以触发一些跟目标Activity不同的功能逻辑，虽然打开的是同一个Activity。举个简单的例子，如之前需要先打开主界面，然后才能点击进入某个Activity，如果使用activity-alias为该Activity配置一个快捷入口，甚至可以为其在桌面生成一个图标，然后点击桌面图标可直接进入该Activity，该功能可满足某些需要快速到达功能界面的需求。</p>
<h3 id="activity-alias语法及声明"><a href="#activity-alias语法及声明" class="headerlink" title="activity-alias语法及声明"></a>activity-alias语法及声明</h3><p>其基本语法如下</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">activity-alias</span> <span class="attr">android:enabled</span>=<span class="string">[</span>&quot;<span class="attr">true</span>&quot; | &quot;<span class="attr">false</span>&quot;]</span></span><br><span class="line"><span class="tag">                <span class="attr">android:exported</span>=<span class="string">[</span>&quot;<span class="attr">true</span>&quot; | &quot;<span class="attr">false</span>&quot;]</span></span><br><span class="line"><span class="tag">                <span class="attr">android:icon</span>=<span class="string">&quot;drawable resource&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">android:label</span>=<span class="string">&quot;string resource&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">android:name</span>=<span class="string">&quot;string&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">android:permission</span>=<span class="string">&quot;string&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">android:targetActivity</span>=<span class="string">&quot;string&quot;</span> &gt;</span></span><br><span class="line">    . . .</span><br><span class="line"><span class="tag">&lt;/<span class="name">activity-alias</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>部分属性说明如下</p>
<ol>
<li> android:enable 该属性用来决定目标Activity可否通过别名被系统实例化，默认为true。需要注意的是application也有enable属性，只用当它们同时为true时，activity-alias的enable才生效。</li>
<li> android:exported 该属性为true的话，则目标Activity可被其他应用调起，如为false则只能被应用自身调起。其默认值根据activity-alias是否包含intent-filter元素决定，如果有的话，则默认为true；没有的话则为false。其实也很好理解，如果有intent-filter，则目标Activity可以匹配隐式Intent，因此可被外部应用唤起；如果没有intent-filter，则目标Activity要被调起的话必须知道其精确类名，因为只有应用本身才知道精确类名，所以此时默认为false。</li>
<li> android:icon 该属性就比较好玩了，允许自定义icon，可以不同于应用本身在桌面的icon。如果需要在桌面上创建快捷入口，也许产品会要求换个不同的icon。</li>
<li> android:label 该属性类似于android:icon，图标都换了，换个名称也合情合理吧，此属性就是为此而生的。</li>
<li> android:name 该属性可以为任意字符串，但最好符合类名命名规范。activity元素的name属性实质上都会指向一个具体的Activity类，而activity-alias的name属性仅作为一个唯一标识而已。</li>
<li> android:permission 该属性指明了通过别名声明调起目标Activity所必需的权限。</li>
<li> android:targetActivity 该属性指定了目标Activity，即通过activity-alias调起的Activity是哪个，此属性其实类似于activity标签中的name属性，需要规范的Activity包名类名。</li>
</ol>
<p>看了以上几个主要属性，大家应该意识到activity-alias的属性是activity属性的子集，如果是activity-alias和activity共有的属性，则以activity-alias为准，目标Activity中的设置并不会在activity-alias中生效；如果是仅activity才有的属性，则为目标Activity配置的属性会在activity-alias中生效。</p>
<p>activity-alias可以设置自己的intent-filter或meta-date，最常用的就是设置如下intent-filter从而在桌面Launcher上创建一个快捷入口：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;intent-filter&gt;</span><br><span class="line">    &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;</span><br><span class="line">    &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;</span><br><span class="line">&lt;/intent-filter&gt;</span><br></pre></td></tr></table></figure>

<p>另外需要注意的一点是，在AndroidManifest配置文件中，activity-alias标签元素必须声明在目标Acitvity对应的activity标签元素之后，否则会编译错误。</p>
<h3 id="activity-alias用法示例"><a href="#activity-alias用法示例" class="headerlink" title="activity-alias用法示例"></a>activity-alias用法示例</h3><p>到此大家已经对activity-alias了解的比较深入了，来看一个activity-alias的经典用法：为某个Activity在桌面创建一个快捷入口。</p>
<p>代码很简单，应用包含两个Activity：MainActivity和SecondActivity，MainActivity有一个Button，点击跳转到SecondActivity；我们为SecondActivity配置一个activity-alias标签元素，在桌面上为其创建一个快捷入口，点击可以直接打开SecondActivity。</p>
<p>该示例应用的AndroidManifest.xml内容如下：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">manifest</span> <span class="attr">xmlns:android</span>=<span class="string">&quot;http://schemas.android.com/apk/res/android&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">package</span>=<span class="string">&quot;me.geed.activityalias&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">application</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:allowBackup</span>=<span class="string">&quot;true&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:icon</span>=<span class="string">&quot;@mipmap/ic_launcher&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:label</span>=<span class="string">&quot;@string/app_name&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:supportsRtl</span>=<span class="string">&quot;true&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:theme</span>=<span class="string">&quot;@style/AppTheme&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">activity</span> <span class="attr">android:name</span>=<span class="string">&quot;.MainActivity&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">action</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.action.MAIN&quot;</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">                <span class="tag">&lt;<span class="name">category</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.category.LAUNCHER&quot;</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">activity</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">activity</span> <span class="attr">android:name</span>=<span class="string">&quot;.SecondActivity&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">activity</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">activity-alias</span></span></span><br><span class="line"><span class="tag">            <span class="attr">android:name</span>=<span class="string">&quot;SecondActivityAlias&quot;</span></span></span><br><span class="line"><span class="tag">            <span class="attr">android:label</span>=<span class="string">&quot;Alias快捷入口&quot;</span></span></span><br><span class="line"><span class="tag">            <span class="attr">android:targetActivity</span>=<span class="string">&quot;.SecondActivity&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">action</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.action.MAIN&quot;</span> /&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">category</span> <span class="attr">android:name</span>=<span class="string">&quot;android.intent.category.LAUNCHER&quot;</span> /&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">intent-filter</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">activity-alias</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">application</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">manifest</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>将应用部署到手机上，你会发现生成了两个桌面图标（此处由于没有为activity-alias另指定icon，因此两者icon相同），名称分别为“ActivityAlias”和“Alias快捷入口”。</p>
<p>点击“ActivityAlias”应用图标，会启动MainActivity，在MainActivity中点击Button，跳转到SecondActivity。</p>
<p>点击“Alias快捷入口”图标，则可以直接打开SecondActivity，且SecondActivity的title为我们在activity-alias中设置的 label属性名称。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/12/%E5%AE%89%E5%8D%93%E5%A4%87%E5%BF%98%EF%BC%9A%E8%B7%B3%E8%BD%AC%E7%B3%BB%E7%BB%9F%E9%A1%B5%E9%9D%A2%E4%BB%A5%E5%8F%8A%E5%B8%B8%E8%A7%81APP%E7%9B%B8%E5%BA%94%E9%A1%B5%E9%9D%A2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/12/%E5%AE%89%E5%8D%93%E5%A4%87%E5%BF%98%EF%BC%9A%E8%B7%B3%E8%BD%AC%E7%B3%BB%E7%BB%9F%E9%A1%B5%E9%9D%A2%E4%BB%A5%E5%8F%8A%E5%B8%B8%E8%A7%81APP%E7%9B%B8%E5%BA%94%E9%A1%B5%E9%9D%A2/" class="post-title-link" itemprop="url">安卓备忘：跳转系统页面以及常见APP相应页面</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-12 20:03:39" itemprop="dateCreated datePublished" datetime="2017-05-12T20:03:39+08:00">2017-05-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>﻿&gt;今天需要写一个跳转到系统拨号页面的功能，其实简单的很，就一句话的事儿。不过念在系统页面众多，于是乎，在此做一个总结，万一以后忘记了，也方便查阅。</p>
<h1 id="系统页面"><a href="#系统页面" class="headerlink" title="系统页面"></a>系统页面</h1><h2 id="跳转浏览器浏览网页"><a href="#跳转浏览器浏览网页" class="headerlink" title="跳转浏览器浏览网页"></a>跳转浏览器浏览网页</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.parse(&quot;http://www.google.com&quot;);   </span><br><span class="line">Intent intent   = new Intent(Intent.ACTION_VIEW,uri);   </span><br><span class="line">startActivity(intent);</span><br></pre></td></tr></table></figure>


<h2 id="拨打电话"><a href="#拨打电话" class="headerlink" title="拨打电话"></a>拨打电话</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">//第一种方法</span><br><span class="line">Uri uri = Uri.parse(&quot;tel:xxxxxx&quot;);   </span><br><span class="line">Intent it = new Intent(Intent.ACTION_DIAL, uri);     </span><br><span class="line">startActivity(it);  </span><br><span class="line">//第二种方法</span><br><span class="line">Uri uri = Uri.parse(&quot;tel:&quot;+number);    </span><br><span class="line">Intent intent = new Intent(Intent.ACTION_CALL,uri);    </span><br><span class="line">startActivity(intent);  </span><br></pre></td></tr></table></figure>

<h2 id="调用发短信的程序"><a href="#调用发短信的程序" class="headerlink" title="调用发短信的程序"></a>调用发短信的程序</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Intent it = new Intent(Intent.ACTION_VIEW);     </span><br><span class="line">it.putExtra(&quot;sms_body&quot;, &quot;The SMS text&quot;);     </span><br><span class="line">it.setType(&quot;vnd.android-dir/mms-sms&quot;);     </span><br><span class="line">startActivity(it);</span><br><span class="line">和</span><br><span class="line">uri = Uri.parse(&quot;smsto:&quot;+要发送短信的对方的number);    </span><br><span class="line">intent = new Intent(Intent.ACTION_SENDTO,uri);    </span><br><span class="line">startActivity(intent);   </span><br><span class="line">和</span><br><span class="line">mIntent = new Intent(Intent.ACTION_VIEW);    </span><br><span class="line">mIntent.putExtra(&quot;address&quot;, c.getString(c.getColumnIndex(column)));    </span><br><span class="line">mIntent.setType(&quot;vnd.android-dir/mms-sms&quot;);    </span><br><span class="line">startActivity(mIntent);   </span><br></pre></td></tr></table></figure>

<h2 id="发送短信"><a href="#发送短信" class="headerlink" title="发送短信"></a>发送短信</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.parse(&quot;smsto:0800000123&quot;);     </span><br><span class="line">Intent it = new Intent(Intent.ACTION_SENDTO, uri);     </span><br><span class="line">it.putExtra(&quot;sms_body&quot;, &quot;The SMS text&quot;);     </span><br><span class="line">startActivity(it);   </span><br><span class="line">String body=&quot;this is sms demo&quot;;   </span><br><span class="line">Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(&quot;smsto&quot;, number, null));   </span><br><span class="line">mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);   </span><br><span class="line">mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);   </span><br><span class="line">mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);   </span><br><span class="line">startActivity(mmsintent);</span><br></pre></td></tr></table></figure>

<h2 id="播放多媒体"><a href="#播放多媒体" class="headerlink" title="播放多媒体"></a>播放多媒体</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Intent it = new Intent(Intent.ACTION_VIEW);   </span><br><span class="line">Uri uri = Uri.parse(&quot;file:///sdcard/song.mp3&quot;);   </span><br><span class="line">it.setDataAndType(uri, &quot;audio/mp3&quot;);   </span><br><span class="line">startActivity(it);   </span><br><span class="line">Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, &quot;1&quot;);     </span><br><span class="line">Intent it = new Intent(Intent.ACTION_VIEW, uri);     </span><br><span class="line">startActivity(it);   </span><br></pre></td></tr></table></figure>

<h2 id="uninstall-apk"><a href="#uninstall-apk" class="headerlink" title="uninstall apk"></a>uninstall apk</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.fromParts(&quot;package&quot;, strPackageName, null);     </span><br><span class="line">Intent it = new Intent(Intent.ACTION_DELETE, uri);     </span><br><span class="line">startActivity(it);  </span><br></pre></td></tr></table></figure>

<h2 id="install-apk"><a href="#install-apk" class="headerlink" title="install apk"></a>install apk</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Uri installUri = Uri.fromParts(&quot;package&quot;, &quot;xxx&quot;, null);   </span><br><span class="line">returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);  </span><br></pre></td></tr></table></figure>

<h2 id="打开照相机"><a href="#打开照相机" class="headerlink" title="打开照相机"></a>打开照相机</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;1&gt;Intent i = new Intent(Intent.ACTION_CAMERA_BUTTON, null);   </span><br><span class="line">          this.sendBroadcast(i);    </span><br><span class="line">&lt;2&gt;long dateTaken = System.currentTimeMillis();   </span><br><span class="line">         String name = createName(dateTaken) + &quot;.jpg&quot;;   </span><br><span class="line">         fileName = folder + name;   </span><br><span class="line">         ContentValues values = new ContentValues();   </span><br><span class="line">         values.put(Images.Media.TITLE, fileName);   </span><br><span class="line">         values.put(&quot;_data&quot;, fileName);   </span><br><span class="line">         values.put(Images.Media.PICASA_ID, fileName);   </span><br><span class="line">         values.put(Images.Media.DISPLAY_NAME, fileName);   </span><br><span class="line">         values.put(Images.Media.DESCRIPTION, fileName);   </span><br><span class="line">         values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, fileName);   </span><br><span class="line">         Uri photoUri = getContentResolver().insert(   </span><br><span class="line">         MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);   </span><br><span class="line"> </span><br><span class="line">         Intent inttPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);   </span><br><span class="line">         inttPhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);   </span><br><span class="line">         startActivityForResult(inttPhoto, 10);</span><br></pre></td></tr></table></figure>

<p>##从gallery选取图片</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Intent i = new Intent();   </span><br><span class="line">   i.setType(&quot;image/*&quot;);   </span><br><span class="line">   i.setAction(Intent.ACTION_GET_CONTENT);   </span><br><span class="line">   startActivityForResult(i, 11);  </span><br></pre></td></tr></table></figure>


<p>##打开录音机</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Intent mi = new Intent(Media.RECORD_SOUND_ACTION);   </span><br><span class="line">startActivity(mi);</span><br></pre></td></tr></table></figure>

<p>##显示应用详细列表</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.parse(&quot;market://details?id=app_id&quot;);          </span><br><span class="line">Intent it = new Intent(Intent.ACTION_VIEW, uri);          </span><br><span class="line">startActivity(it);          </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">//where app_id is the application ID, find the ID           </span><br><span class="line">//by clicking on your application on Market home           </span><br><span class="line">//page, and notice the ID from the address bar</span><br></pre></td></tr></table></figure>
<p>刚才找app id未果，结果发现用package name也可以 Uri uri = Uri.parse(“market://details?id=<packagename>“);<br>这个简单多了 </p>
<h2 id="寻找应用"><a href="#寻找应用" class="headerlink" title="寻找应用"></a>寻找应用</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.parse(&quot;market://search?q=pname:pkg_name&quot;);          </span><br><span class="line">Intent it = new Intent(Intent.ACTION_VIEW, uri);          </span><br><span class="line">startActivity(it);   </span><br><span class="line">//where pkg_name is the full package path for an application</span><br></pre></td></tr></table></figure>

<p>##打开联系人列表</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Intent i = new Intent();   </span><br><span class="line">    i.setAction(Intent.ACTION_GET_CONTENT);   </span><br><span class="line">    i.setType(&quot;vnd.android.cursor.item/phone&quot;);   </span><br><span class="line">    startActivityForResult(i, REQUEST_TEXT);</span><br><span class="line">    Uri uri = Uri.parse(&quot;content://contacts/people&quot;);   </span><br><span class="line">    Intent it = new Intent(Intent.ACTION_PICK, uri);   </span><br><span class="line">    startActivityForResult(it, REQUEST_TEXT);</span><br></pre></td></tr></table></figure>


<p>##打开另一程序</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Intent i = new Intent();   </span><br><span class="line">ComponentName cn = new ComponentName(&quot;com.yellowbook.android2&quot;,   &quot;com.yellowbook.android2.AndroidSearch&quot;);   </span><br><span class="line">i.setComponent(cn);    </span><br><span class="line">i.setAction(&quot;android.intent.action.MAIN&quot;);   </span><br><span class="line">startActivityForResult(i, RESULT_OK);  </span><br></pre></td></tr></table></figure>

<h2 id="添加到短信收件箱"><a href="#添加到短信收件箱" class="headerlink" title="添加到短信收件箱"></a>添加到短信收件箱</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ContentValues cv = new ContentValues();      </span><br><span class="line">cv.put(&quot;type&quot;, &quot;1&quot;);   </span><br><span class="line">cv.put(&quot;address&quot;,&quot;短信地址&quot;);  </span><br><span class="line">cv.put(&quot;body&quot;, &quot;短信内容&quot;);   </span><br><span class="line">getContentResolver().insert(Uri.parse(&quot;content://sms/inbox&quot;), cv);</span><br></pre></td></tr></table></figure>

<p>##从sim卡或者联系人中查询</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Cursor cursor;  </span><br><span class="line">Uri uri;  </span><br><span class="line">if (type == 1) &#123;  </span><br><span class="line">Intent intent = new Intent();  </span><br><span class="line">intent.setData(Uri.parse(&quot;content://icc/adn&quot;));  </span><br><span class="line">uri = intent.getData();  </span><br><span class="line">&#125; else  </span><br><span class="line">uri = People.CONTENT_URI;  </span><br><span class="line">cursor = activity.getContentResolver().query(uri, null, null, null, null);  </span><br><span class="line">while (cursor.moveToNext()) &#123;  </span><br><span class="line">int peopleId = cursor.getColumnIndex(People._ID);</span><br><span class="line">int nameId = cursor.getColumnIndex(People.NAME); </span><br><span class="line">int phoneId = cursor.getColumnIndex(People.NUMBER);&#125;</span><br><span class="line">查看某个联系人，当然这里是ACTION_VIEW，如果为选择并返回action改为ACTION_PICK，当然处理intent时返回需要用到 startActivityforResult </span><br><span class="line">Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, ID);//最后的ID参数为联系人Provider中的数据库BaseID，即哪一行 </span><br><span class="line">Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(personUri); startActivity(intent); </span><br></pre></td></tr></table></figure>

<p>##删除</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">uri = ContentUris.withAppendedId(People.CONTENT_URI, 联系人id);  </span><br><span class="line">int count = activity.getContentResolver().delete(uri, null, null</span><br></pre></td></tr></table></figure>

<h2 id="添加到联系人："><a href="#添加到联系人：" class="headerlink" title="添加到联系人："></a>添加到联系人：</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">ContentValues cv = new ContentValues();  </span><br><span class="line">ArrayList&lt;ContentProviderOperation&gt; operationList = new ArrayList&lt;ContentProviderOperation&gt;();  </span><br><span class="line">ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);  </span><br><span class="line">builder.withValues(cv);  </span><br><span class="line">operationList.add(builder.build());  </span><br><span class="line">builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);  </span><br><span class="line">builder.withValueBackReference(StructuredName.RAW_CONTACT_ID, 0);  </span><br><span class="line">builder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);  </span><br><span class="line">builder.withValue(StructuredName.DISPLAY_NAME, &quot;自定义联系人名&quot;);  </span><br><span class="line">operationList.add(builder.build());  </span><br><span class="line">builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);  </span><br><span class="line">builder.withValueBackReference(Phone.RAW_CONTACT_ID, 0);  </span><br><span class="line">builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);  </span><br><span class="line">builder.withValue(Phone.NUMBER, &quot;联系人的phonenumber&quot;);  </span><br><span class="line">builder.withValue(Data.IS_PRIMARY, 1);  </span><br><span class="line">operationList.add(builder.build());  </span><br><span class="line">try &#123;  </span><br><span class="line">          getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList);  </span><br><span class="line">       &#125; catch (RemoteException e) &#123;  </span><br><span class="line">           e.printStackTrace();  </span><br><span class="line">       &#125; catch (OperationApplicationException e) &#123;  </span><br><span class="line">         e.printStackTrace();  </span><br><span class="line">     &#125;  </span><br></pre></td></tr></table></figure>

<p>##选择一个图片</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Intent intent = new Intent(Intent.ACTION_GET_CONTENT);   </span><br><span class="line">intent.addCategory(Intent.CATEGORY_OPENABLE);  </span><br><span class="line">intent.setType(&quot;image/*&quot;);  </span><br><span class="line">startActivityForResult(intent, 0);   </span><br></pre></td></tr></table></figure>

<h2 id="调用Android设备的照相机，并设置拍照后存放位置"><a href="#调用Android设备的照相机，并设置拍照后存放位置" class="headerlink" title="调用Android设备的照相机，并设置拍照后存放位置"></a>调用Android设备的照相机，并设置拍照后存放位置</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  </span><br><span class="line">intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment .getExternalStorageDirectory().getAbsolutePath()+&quot;/cwj&quot;, android123 + &quot;.jpg&quot;))); //存放位置为sdcard卡上cwj文件夹，文件名为android123.jpg格式  </span><br><span class="line">startActivityForResult(intent, 0);  </span><br></pre></td></tr></table></figure>

<h2 id="在market上搜索指定package-name，"><a href="#在market上搜索指定package-name，" class="headerlink" title="在market上搜索指定package name，"></a>在market上搜索指定package name，</h2><p>比如搜索com.android123.cwj的写法如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Uri uri = Uri.parse(&quot;market://search?q=pname:com.android123.cwj&quot;);   </span><br><span class="line">Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);</span><br></pre></td></tr></table></figure>


<p>##获取文件信息，并使用相对应软件打开</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">private void openFile(File f)    </span><br><span class="line">&#123;    </span><br><span class="line">   Intent intent = new Intent();    </span><br><span class="line">   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    </span><br><span class="line">   intent.setAction(android.content.Intent.ACTION_VIEW);    </span><br><span class="line">   String type = getMIMEType(f);    </span><br><span class="line">   intent.setDataAndType(Uri.fromFile(f), type);    </span><br><span class="line">   startActivity(intent);    </span><br><span class="line">&#125;    </span><br><span class="line">private String getMIMEType(File f)&#123;    </span><br><span class="line">   String end = f  .getName() .substring(f.getName().lastIndexOf(&quot;.&quot;) + 1,f.getName().length()).toLowerCase();    </span><br><span class="line">  String type = &quot;&quot;;    </span><br><span class="line">  if (end.equals(&quot;mp3&quot;) || end.equals(&quot;aac&quot;) || end.equals(&quot;aac&quot;)|| end.equals(&quot;amr&quot;) || end.equals(&quot;mpeg&quot;)|| end.equals(&quot;mp4&quot;))    </span><br><span class="line">  &#123;    </span><br><span class="line">     type = &quot;audio&quot;;    </span><br><span class="line">  &#125;</span><br><span class="line">  else if (end.equals(&quot;jpg&quot;) || end.equals(&quot;gif&quot;)|| end.equals(&quot;png&quot;) || end.equals(&quot;jpeg&quot;))    </span><br><span class="line">  &#123; </span><br><span class="line">     type = &quot;image&quot;;    </span><br><span class="line">   &#125;</span><br><span class="line">  else    </span><br><span class="line">  &#123;    </span><br><span class="line">     type = &quot;*&quot;;    </span><br><span class="line">  &#125;    </span><br><span class="line">     type += &quot;/*&quot;;     </span><br><span class="line">     return type;    </span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>
<h1 id="三方页面"><a href="#三方页面" class="headerlink" title="三方页面"></a>三方页面</h1><p>三方应用在跳转前应该首先进行跳转之前的检查。检测该APP是否已经安装。如果安装再进行跳转，否则可能会出现异常而崩溃。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">//检查某APP是否安装</span><br><span class="line">    public static boolean isAvilible(Context context, String packageName)&#123;   </span><br><span class="line">        //获取packagemanager   </span><br><span class="line">        final PackageManager packageManager = context.getPackageManager();  </span><br><span class="line">      //获取所有已安装程序的包信息   </span><br><span class="line">        List&lt;PackageInfo&gt; packageInfos = packageManager.getInstalledPackages(0);  </span><br><span class="line">      //用于存储所有已安装程序的包名   </span><br><span class="line">        List&lt;String&gt; packageNames = new ArrayList&lt;String&gt;();  </span><br><span class="line">        //从pinfo中将包名字逐一取出，压入pName list中   </span><br><span class="line">        if(packageInfos != null)&#123;   </span><br><span class="line">            for(int i = 0; i &lt; packageInfos.size(); i++)&#123;   </span><br><span class="line">                String packName = packageInfos.get(i).packageName;   </span><br><span class="line">                packageNames.add(packName);   </span><br><span class="line">            &#125;   </span><br><span class="line">        &#125;   </span><br><span class="line">      //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE   </span><br><span class="line">        return packageNames.contains(packageName);  </span><br><span class="line">  &#125;  </span><br></pre></td></tr></table></figure>

<h2 id="跳转高德地图"><a href="#跳转高德地图" class="headerlink" title="跳转高德地图"></a>跳转高德地图</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Intent intent = Intent.getIntent(&quot;androidamap://viewMap?sourceApplication=地址&amp;poiname=XX大厦&amp;lat=39.045967&amp;lon=118.93526&amp;dev=0&quot;);  </span><br><span class="line">startActivity(intent);  </span><br></pre></td></tr></table></figure>

<h2 id="跳转添加QQ好友页面"><a href="#跳转添加QQ好友页面" class="headerlink" title="跳转添加QQ好友页面"></a>跳转添加QQ好友页面</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String url = &quot;mqqwpa://im/chat?chat_type=wpa&amp;uin=2318723605&quot;;//uin是发送过去的qq号码</span><br><span class="line">startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));</span><br></pre></td></tr></table></figure>




      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/12/%E5%AE%89%E5%8D%93%EF%BC%9AFragment%E7%9A%84%E6%87%92%E5%8A%A0%E8%BD%BD/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/12/%E5%AE%89%E5%8D%93%EF%BC%9AFragment%E7%9A%84%E6%87%92%E5%8A%A0%E8%BD%BD/" class="post-title-link" itemprop="url">安卓：Fragment的懒加载</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-12 20:03:39" itemprop="dateCreated datePublished" datetime="2017-05-12T20:03:39+08:00">2017-05-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>﻿Android应用开发过程中，ViewPager同时加载多个fragment，以实现多tab页面快速切换, 但是fragment初始化时若加载的内容较多，就可能导致整个应用启动速度缓慢，影响用户体验。<br>为了提高用户体验，我们会使用一些懒加载方案，实现加载延迟。这时我们会用到getUserVisibleHint()与setUserVisibleHint()这两个方法。</p>
<h1 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h1><p>首先先从Fragment的生命周期开始说起，讲一讲Fragment每个生命周期方法的意义、作用：</p>
<h3 id="setUserVisibleHint-："><a href="#setUserVisibleHint-：" class="headerlink" title="setUserVisibleHint()："></a>setUserVisibleHint()：</h3><p>设置Fragment可见或者不可见时会调用此方法。在该方法里面可以通过调用getUserVisibleHint()获得Fragment的状态是可见还是不可见的，如果可见则进行懒加载操作。</p>
<h3 id="onAttach-："><a href="#onAttach-：" class="headerlink" title="onAttach()："></a>onAttach()：</h3><p>执行该方法时，Fragment与Activity已经完成绑定，该方法有一个Activity类型的参数，代表绑定的Activity，这时候你可以执行诸如mActivity = activity的操作。</p>
<h3 id="onCreate-："><a href="#onCreate-：" class="headerlink" title="onCreate()："></a>onCreate()：</h3><p>初始化Fragment。可通过参数savedInstanceState获取之前保存的值。</p>
<h3 id="onCreateView-："><a href="#onCreateView-：" class="headerlink" title="onCreateView()："></a>onCreateView()：</h3><p>初始化Fragment的布局。加载布局和findViewById的操作通常在此函数内完成，但是不建议执行耗时的操作，比如读取数据库数据列表。</p>
<h3 id="onActivityCreated-："><a href="#onActivityCreated-：" class="headerlink" title="onActivityCreated()："></a>onActivityCreated()：</h3><p>执行该方法时，与Fragment绑定的Activity的onCreate方法已经执行完成并返回，在该方法内可以进行与Activity交互的UI操作，所以在该方法之前Activity的onCreate方法并未执行完成，如果提前进行交互操作，会引发空指针异常。</p>
<h3 id="onStart-："><a href="#onStart-：" class="headerlink" title="onStart()："></a>onStart()：</h3><p>执行该方法时，Fragment由不可见变为可见状态。</p>
<h3 id="onResume-："><a href="#onResume-：" class="headerlink" title="onResume()："></a>onResume()：</h3><p>执行该方法时，Fragment处于活动状态，用户可与之交互。</p>
<h3 id="onPause-："><a href="#onPause-：" class="headerlink" title="onPause()："></a>onPause()：</h3><p>执行该方法时，Fragment处于暂停状态，但依然可见，用户不能与之交互。</p>
<h3 id="onSaveInstanceState-："><a href="#onSaveInstanceState-：" class="headerlink" title="onSaveInstanceState()："></a>onSaveInstanceState()：</h3><p>保存当前Fragment的状态。该方法会自动保存Fragment的状态，比如EditText键入的文本，即使Fragment被回收又重新创建，一样能恢复EditText之前键入的文本。</p>
<h3 id="onStop-："><a href="#onStop-：" class="headerlink" title="onStop()："></a>onStop()：</h3><p>执行该方法时，Fragment完全不可见。</p>
<h3 id="onDestroyView-："><a href="#onDestroyView-：" class="headerlink" title="onDestroyView()："></a>onDestroyView()：</h3><p>销毁与Fragment有关的视图，但未与Activity解除绑定，依然可以通过onCreateView方法重新创建视图。通常在ViewPager+Fragment的方式下会调用此方法。</p>
<h3 id="onDestroy-："><a href="#onDestroy-：" class="headerlink" title="onDestroy()："></a>onDestroy()：</h3><p>销毁Fragment。通常按Back键退出或者Fragment被回收时调用此方法。</p>
<h3 id="onDetach-："><a href="#onDetach-：" class="headerlink" title="onDetach()："></a>onDetach()：</h3><p>解除与Activity的绑定。在onDestroy方法之后调用。</p>
<p>Fragment生命周期执行流程：<br>Fragment创建：setUserVisibleHint()-&gt;onAttach()-&gt;onCreate()-&gt;onCreateView()-&gt;onActivityCreated()-&gt;onStart()-&gt;onResume()；<br>Fragment变为不可见状态（锁屏、回到桌面、被Activity完全覆盖）：onPause()-&gt;onSaveInstanceState()-&gt;onStop()；<br>Fragment变为部分可见状态（打开Dialog样式的Activity）：onPause()-&gt;onSaveInstanceState()；<br>Fragment由不可见变为活动状态：onStart()-&gt;OnResume()；<br>Fragment由部分可见变为活动状态：onResume()；<br>退出应用：onPause()-&gt;onStop()-&gt;onDestroyView()-&gt;onDestroy()-&gt;onDetach()（注意退出不会调用onSaveInstanceState方法，因为是人为退出，没有必要再保存数据）；<br>Fragment被回收又重新创建：被回收执行onPause()-&gt;onSaveInstanceState()-&gt;onStop()-&gt;onDestroyView()-&gt;onDestroy()-&gt;onDetach()，重新创建执行onAttach()-&gt;onCreate()-&gt;onCreateView()-&gt;onActivityCreated()-&gt;onStart()-&gt;onResume()-&gt;setUserVisibleHint()；<br>横竖屏切换：与Fragment被回收又重新创建一样。</p>
<h1 id="看一下源码"><a href="#看一下源码" class="headerlink" title="看一下源码"></a>看一下源码</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">*</span></span><br><span class="line"><span class="comment">* <span class="doctag">@param</span> isVisibleToUser true if this fragment&#x27;s UI is currently visible to the user (default),</span></span><br><span class="line"><span class="comment">*                        false if it is not.</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUserVisibleHint</span><span class="params">(<span class="keyword">boolean</span> isVisibleToUser)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (!mUserVisibleHint &amp;&amp; isVisibleToUser &amp;&amp; mState &lt; STARTED) &#123;</span><br><span class="line">       mFragmentManager.performPendingDeferredStart(<span class="keyword">this</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   mUserVisibleHint = isVisibleToUser;</span><br><span class="line">   mDeferStart = !isVisibleToUser;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> The current value of the user-visible hint on this fragment.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setUserVisibleHint(boolean)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">getUserVisibleHint</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> mUserVisibleHint;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从上述源码注释我们可以看出，当fragment被用户可见时，setUserVisibleHint()会调用且传入true值，当fragment不被用户可见时，setUserVisibleHint()则得到false值。而在传统的fragment生命周期里也看不到这个函数。</p>
<p><img src="http://img.blog.csdn.net/20160428203327414" alt="fragment生命周期"> </p>
<p>那么，问题来了，<br>fragment是如何知道自己时候用户可见？<br>setUserVisibleHint() 在上图所示fragment的生命周期的什么位置?</p>
<p><strong>先说结论：</strong></p>
<ol>
<li>viewpager监听切换tab事件，tab切换一次，执行一次setUserVisibleHint()方法</li>
<li>setUserVisibleHint() 在 上图所示fragment所有生命周期之前，无论viewpager是在activity哪个生命周期里初始化。</li>
<li>activity生命周期 和 fragment生命周期 时序并不是按序来的，也就是说fragment的oncreate方法时序并不一定在activity的oncreate方法之后。</li>
</ol>
<p>具体原因，我们从应用场景开始一点一点的分析。</p>
<h2 id="1-我们的使用场景："><a href="#1-我们的使用场景：" class="headerlink" title="1. 我们的使用场景："></a>1. 我们的使用场景：</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">FragmentActivity</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ViewPager viewPager;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line"></span><br><span class="line">        viewPager = (ViewPager) findViewById(R.id.viewpager);</span><br><span class="line">        vpOrder.setAdapter(<span class="keyword">new</span> MainFragmentPagerAdapter(getSupportFragmentManager()));</span><br><span class="line">        vpOrder.setOffscreenPageLimit(<span class="number">5</span>);</span><br><span class="line">        vpOrder.setCurrentItem(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">｝</span><br></pre></td></tr></table></figure>
<h2 id="2-ViewPager-FragmentPagerAdapter"><a href="#2-ViewPager-FragmentPagerAdapter" class="headerlink" title="2.ViewPager ,FragmentPagerAdapter"></a>2.ViewPager ,FragmentPagerAdapter</h2><ul>
<li>/frameworks/base/core/java/android/app/Activity.java<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//每次切换ViewPager的Tab时调用的方法</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">populate</span><span class="params">(<span class="keyword">int</span> newCurrentItem)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        mAdapter.startUpdate(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//......</span></span><br><span class="line">        addNewItem(mCurItem, curIndex);</span><br><span class="line">        <span class="comment">// mCurItem 为当前可见Fragment</span></span><br><span class="line">        <span class="comment">// 调用setUserVisibleHint(true)</span></span><br><span class="line">        mAdapter.setPrimaryItem(<span class="keyword">this</span>, mCurItem, curItem != <span class="keyword">null</span> ? curItem.object : <span class="keyword">null</span>); </span><br><span class="line"></span><br><span class="line">        mAdapter.finishUpdate(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//.....</span></span><br><span class="line"></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function">ItemInfo <span class="title">addNewItem</span><span class="params">(<span class="keyword">int</span> position, <span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">        ItemInfo ii = <span class="keyword">new</span> ItemInfo();</span><br><span class="line">        ii.position = position;</span><br><span class="line">        <span class="comment">//初始化fragment, 调用setUserVisibleHint(false)</span></span><br><span class="line">        ii.object = mAdapter.instantiateItem(<span class="keyword">this</span>, position);</span><br><span class="line">        ii.widthFactor = mAdapter.getPageWidth(position);</span><br><span class="line">        <span class="keyword">if</span> (index &lt; <span class="number">0</span> || index &gt;= mItems.size()) &#123;</span><br><span class="line">            mItems.add(ii);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            mItems.add(index, ii);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> ii;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-Activity-FragmentManager"><a href="#3-Activity-FragmentManager" class="headerlink" title="3.  Activity , FragmentManager"></a>3.  Activity , FragmentManager</h2></li>
<li>/frameworks/support/v4/java/android/support/v4/app/FragmentManager.java<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">   <span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">instantiateItem</span><span class="params">(ViewGroup container, <span class="keyword">int</span> position)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (mCurTransaction == <span class="keyword">null</span>) &#123;</span><br><span class="line">        mCurTransaction = mFragmentManager.beginTransaction();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">long</span> itemId = getItemId(position);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Do we already have this fragment?</span></span><br><span class="line">    String name = makeFragmentName(container.getId(), itemId);</span><br><span class="line">    Fragment fragment = mFragmentManager.findFragmentByTag(name);</span><br><span class="line">    <span class="keyword">if</span> (fragment != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (DEBUG) Log.v(TAG, <span class="string">&quot;Attaching item #&quot;</span> + itemId + <span class="string">&quot;: f=&quot;</span> + fragment);</span><br><span class="line">        mCurTransaction.attach(fragment);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fragment = getItem(position);</span><br><span class="line">        <span class="keyword">if</span> (DEBUG) Log.v(TAG, <span class="string">&quot;Adding item #&quot;</span> + itemId + <span class="string">&quot;: f=&quot;</span> + fragment);</span><br><span class="line">        <span class="comment">//将fragment添加到FragmentManager里面</span></span><br><span class="line">        mCurTransaction.add(container.getId(), fragment,</span><br><span class="line">                makeFragmentName(container.getId(), itemId));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (fragment != mCurrentPrimaryItem) &#123;</span><br><span class="line">        fragment.setMenuVisibility(<span class="keyword">false</span>);</span><br><span class="line">        <span class="comment">//我们要找的方法在这里</span></span><br><span class="line">        fragment.setUserVisibleHint(<span class="keyword">false</span>); </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> fragment;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPrimaryItem</span><span class="params">(ViewGroup container, <span class="keyword">int</span> position, Object object)</span> </span>&#123;</span><br><span class="line">    Fragment fragment = (Fragment)object;</span><br><span class="line">    <span class="keyword">if</span> (fragment != mCurrentPrimaryItem) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mCurrentPrimaryItem != <span class="keyword">null</span>) &#123;</span><br><span class="line">            mCurrentPrimaryItem.setMenuVisibility(<span class="keyword">false</span>);</span><br><span class="line">            mCurrentPrimaryItem.setUserVisibleHint(<span class="keyword">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (fragment != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//我们要找的方法在这里</span></span><br><span class="line">            fragment.setMenuVisibility(<span class="keyword">true</span>);</span><br><span class="line">            fragment.setUserVisibleHint(<span class="keyword">true</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        mCurrentPrimaryItem = fragment;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
<p>/frameworks/support/v4/java/android/support/v4/app/FragmentManager.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//分发onCreate事件函数</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">dispatchCreate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    mStateSaved = <span class="keyword">false</span>;</span><br><span class="line">    moveToState(Fragment.CREATED, <span class="keyword">false</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//moveToState 重载 1</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">moveToState</span><span class="params">(<span class="keyword">int</span> newState, <span class="keyword">boolean</span> always)</span> </span>&#123;</span><br><span class="line">    moveToState(newState, <span class="number">0</span>, <span class="number">0</span>, always);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//moveToState 重载 2</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">moveToState</span><span class="params">(<span class="keyword">int</span> newState, <span class="keyword">int</span> transit, <span class="keyword">int</span> transitStyle, <span class="keyword">boolean</span> always)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (mHost == <span class="keyword">null</span> &amp;&amp; newState != Fragment.INITIALIZING) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;No host&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!always &amp;&amp; mCurState == newState) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    mCurState = newState;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//若mActive为null,就算Activtiy里面调用了dispatchOnCreate()也不会执行Fragment</span></span><br><span class="line">    <span class="comment">//的OnAttach和onCreate等方法。</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//只有mActive非null,即addFragment()执行后，才会真正进入到生命周期。</span></span><br><span class="line">    <span class="comment">//而根据FragmentPagerAdapter可知，只有当viewpager调用setAdapter方法，才会添加fragment到FramentManager。</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行setAdapter的时候，会调用setUserVisibleHint()方法，并且，只有当setAdapter方法执行完之后，才会进入到Fragment到生命周期，因此setUserVisibleHint()方法在所有生命周期之前被调用。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mActive != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">boolean</span> loadersRunning = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;mActive.size(); i++) &#123;</span><br><span class="line">            Fragment f = mActive.get(i);</span><br><span class="line">            <span class="keyword">if</span> (f != <span class="keyword">null</span>) &#123;</span><br><span class="line">                moveToState(f, newState, transit, transitStyle, <span class="keyword">false</span>);</span><br><span class="line">                <span class="keyword">if</span> (f.mLoaderManager != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    loadersRunning |= f.mLoaderManager.hasRunningLoaders();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!loadersRunning) &#123;</span><br><span class="line">            startPendingDeferredFragments();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (mNeedMenuInvalidate &amp;&amp; mHost != <span class="keyword">null</span> &amp;&amp; mCurState == Fragment.RESUMED) &#123;</span><br><span class="line">            mHost.onSupportInvalidateOptionsMenu();</span><br><span class="line">            mNeedMenuInvalidate = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//moveToState 重载 3</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">moveToState</span><span class="params">(Fragment f, <span class="keyword">int</span> newState, <span class="keyword">int</span> transit, <span class="keyword">int</span> transitionStyle,</span></span></span><br><span class="line"><span class="params"><span class="function"></span></span></span><br><span class="line"><span class="params"><span class="function">         //...</span></span></span><br><span class="line"><span class="params"><span class="function"></span></span></span><br><span class="line"><span class="params"><span class="function">         f.onAttach()</span></span>;</span><br><span class="line"></span><br><span class="line">         <span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">         f.performOnCreate();</span><br><span class="line"></span><br><span class="line">         <span class="comment">//其他生命周期</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//添加fragment到FragmentManager</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addFragment</span><span class="params">(Fragment fragment, <span class="keyword">boolean</span> moveToStateNow)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (mAdded == <span class="keyword">null</span>) &#123;</span><br><span class="line">        mAdded = <span class="keyword">new</span> ArrayList&lt;Fragment&gt;();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (DEBUG) Log.v(TAG, <span class="string">&quot;add: &quot;</span> + fragment);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//激活fragment</span></span><br><span class="line">    makeActive(fragment);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!fragment.mDetached) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mAdded.contains(fragment)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Fragment already added: &quot;</span> + fragment);</span><br><span class="line">        &#125;</span><br><span class="line">        mAdded.add(fragment);</span><br><span class="line">        fragment.mAdded = <span class="keyword">true</span>;</span><br><span class="line">        fragment.mRemoving = <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (fragment.mHasMenu &amp;&amp; fragment.mMenuVisible) &#123;</span><br><span class="line">            mNeedMenuInvalidate = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (moveToStateNow) &#123;</span><br><span class="line">            moveToState(fragment);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">makeActive</span><span class="params">(Fragment f)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (f.mIndex &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mAvailIndices == <span class="keyword">null</span> || mAvailIndices.size() &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mActive == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//激活Fragment</span></span><br><span class="line">            mActive = <span class="keyword">new</span> ArrayList&lt;Fragment&gt;();    </span><br><span class="line">        &#125;</span><br><span class="line">        f.setIndex(mActive.size(), mParent);</span><br><span class="line">        mActive.add(f);</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        f.setIndex(mAvailIndices.remove(mAvailIndices.size()-<span class="number">1</span>), mParent);</span><br><span class="line">        mActive.set(f.mIndex, f);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (DEBUG) Log.v(TAG, <span class="string">&quot;Allocated fragment index &quot;</span> + f);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/12/%E5%AE%89%E5%8D%93%EF%BC%9A%E4%B8%80%E4%B8%AA%E9%A1%B9%E7%9B%AE%E7%9A%84%E5%A4%9A%E7%A7%8D%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/12/%E5%AE%89%E5%8D%93%EF%BC%9A%E4%B8%80%E4%B8%AA%E9%A1%B9%E7%9B%AE%E7%9A%84%E5%A4%9A%E7%A7%8D%E6%89%93%E5%8C%85%E6%96%B9%E5%BC%8F/" class="post-title-link" itemprop="url">安卓：一个项目的多种打包方式</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-12 20:03:39" itemprop="dateCreated datePublished" datetime="2017-05-12T20:03:39+08:00">2017-05-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <blockquote>
<p>应用场景：工作中经常会遇到一个项目需要多种打包的情况。只改几个参数，或者替换几个图片，就需要重新打一个安装包。如果只是一处两处，一次两次还好，如果频繁有这样的需求，想想就脑壳子疼……</p>
<p>为了解决这个问题， 采用gradle自带的 <strong>productFlavors</strong> 工具来实现多渠道，多app打包方式进行。</p>
</blockquote>
<h2 id="productFlavors是什么？"><a href="#productFlavors是什么？" class="headerlink" title="productFlavors是什么？"></a>productFlavors是什么？</h2><p>直译过来是产品特色，作用也差不多，用同一套代码生成不同的特色的产品。<br>别的也没有必要去深究，简单来说，记住几点就好：</p>
<blockquote>
<ol>
<li>这是gradle自带的工具，在build.gradle里进行配置，主要用于多渠道打包；</li>
<li>能配置非常多的参数，applicationId、versionCode、versionName、签名、资源文件、常量、代码文件等等。</li>
<li>打包时选择配置。</li>
</ol>
</blockquote>
<h2 id="简单使用"><a href="#简单使用" class="headerlink" title="简单使用"></a>简单使用</h2><p>如果只有几个常量需要修改，那么两步就行了：<br>第一步：模块build.gradle 中android下添加如下代码。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">flavorDimensions &quot;default&quot;</span><br><span class="line">productFlavors &#123;</span><br><span class="line">    oneApk &#123;</span><br><span class="line">        buildConfigField &quot;String&quot;, &quot;myString&quot;, &#x27;&quot;第一个apk的文本&quot;&#x27;  </span><br><span class="line">        buildConfigField &quot;int&quot;, &quot;myint&quot;, &#x27;1&#x27;</span><br><span class="line">        buildConfigField &quot;boolean&quot;, &quot;myboolean&quot;, &#x27;false&#x27;</span><br><span class="line">    &#125;</span><br><span class="line">    twoApk &#123;</span><br><span class="line">        buildConfigField &quot;String&quot;, &quot;myString&quot;, &#x27;&quot;第二个apk的文本&quot;&#x27;  </span><br><span class="line">        buildConfigField &quot;int&quot;, &quot;myint&quot;, &#x27;2&#x27;</span><br><span class="line">        buildConfigField &quot;boolean&quot;, &quot;myboolean&quot;, &#x27;true&#x27;</span><br><span class="line">    &#125;</span><br><span class="line">    threeApk &#123;</span><br><span class="line">        buildConfigField &quot;String&quot;, &quot;myString&quot;, &#x27;&quot;第三个apk的文本&quot;&#x27;  </span><br><span class="line">        buildConfigField &quot;int&quot;, &quot;myint&quot;, &#x27;3&#x27;</span><br><span class="line">        buildConfigField &quot;boolean&quot;, &quot;myboolean&quot;, &#x27;false&#x27;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第二步：clean之后重新编译，代码中直接就可以使用了</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Log.e(&quot;mystring&quot;,BuildConfig.myString);</span><br></pre></td></tr></table></figure>
<p><strong>打包之前在Android Studio左侧底部找到Build Variants栏，选择对应的Build Variant打包。</strong></p>
<h2 id="高阶使用"><a href="#高阶使用" class="headerlink" title="高阶使用"></a>高阶使用</h2><h3 id="修改applicationId、versionCode、versionName、签名……"><a href="#修改applicationId、versionCode、versionName、签名……" class="headerlink" title="修改applicationId、versionCode、versionName、签名……"></a>修改applicationId、versionCode、versionName、签名……</h3><p>在上面那段代码的基础上修改就行，每一个productFlavors 中进行相应的设置。<br>为了以后能直接复制粘贴用，那我现在复制一下吧！</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">flavorDimensions &quot;default&quot;</span><br><span class="line">  productFlavors &#123;</span><br><span class="line">      oneApk &#123;</span><br><span class="line">          applicationId &quot;com.xx.xxone&quot;</span><br><span class="line">          versionCode 1</span><br><span class="line">          versionName &quot;1.1&quot;</span><br><span class="line">          signingConfig signingConfigs.oneRelease</span><br><span class="line">          </span><br><span class="line">          //....</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      twoApk &#123;</span><br><span class="line">          applicationId &quot;com.xx.xxtwo&quot;</span><br><span class="line">          versionCode 2</span><br><span class="line">          versionName &quot;1.2&quot;</span><br><span class="line">          signingConfig signingConfigs.twoRelease</span><br><span class="line"></span><br><span class="line">          //....</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      threeApk &#123;</span><br><span class="line">          applicationId &quot;com.xx.xxthree&quot;</span><br><span class="line">          versionCode 3</span><br><span class="line">          versionName &quot;1.3&quot;</span><br><span class="line">          signingConfig signingConfigs.threeRelease</span><br><span class="line"></span><br><span class="line">           //....</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  // 因为多了签名，所以还得多一个标签，如下:</span><br><span class="line">  signingConfigs &#123;</span><br><span class="line">      oneRelease &#123;</span><br><span class="line">          storeFile file(&quot;xx/xx/one.jks&quot;) // 签名文件路径</span><br><span class="line">          storePassword &quot;123456&quot;</span><br><span class="line">          keyAlias &quot;one&quot;</span><br><span class="line">          keyPassword &quot;123456&quot;</span><br><span class="line">      &#125;</span><br><span class="line">      twoRelease &#123;</span><br><span class="line">          storeFile file(&quot;xx/xx/two.jks&quot;)</span><br><span class="line">          storePassword &quot;123456&quot;</span><br><span class="line">          keyAlias &quot;two&quot;</span><br><span class="line">          keyPassword &quot;123456&quot;</span><br><span class="line">      &#125;</span><br><span class="line">      threeRelease &#123;</span><br><span class="line">          storeFile file(&quot;xx/xx/three.jks&quot;)</span><br><span class="line">          storePassword &quot;123456&quot;</span><br><span class="line">          keyAlias &quot;three&quot;</span><br><span class="line">          keyPassword &quot;123456&quot;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>如果修改签名不成功，还是用了默认的签名，那么把buildTypes下 signingConfig设置为 null 即可。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">buildTypes &#123;</span><br><span class="line">       release &#123;</span><br><span class="line">           signingConfig null</span><br><span class="line">           //... 省略其它</span><br><span class="line">       &#125;</span><br><span class="line">       debug &#123;</span><br><span class="line">           signingConfig null</span><br><span class="line">            //... 省略其它</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h2 id="其它"><a href="#其它" class="headerlink" title="其它"></a>其它</h2><p>渠道多了，打包的时候很容易乱，因此打包的时候区分一下apk的文件名。</p>
<p>buiild.gradle最外层标签添加时间方法</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">static def releaseTime() &#123;</span><br><span class="line">    return new Date().format(&quot;yyyy-MM-dd-HH.mm&quot;, TimeZone.getTimeZone(&quot;GMT+8&quot;))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>android标签下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">applicationVariants.all &#123;</span><br><span class="line">    variant -&gt;</span><br><span class="line">        variant.outputs.all &#123;</span><br><span class="line">            outputFileName = &quot;$&#123;variant.productFlavors[0].name&#125;-v$&#123;variant.productFlavors[0].versionName&#125;-$&#123;releaseTime()&#125;.apk&quot;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/12/%E8%AF%A6%E7%BB%86%E8%AE%B2%E8%A7%A3%E5%AE%89%E5%8D%93%E6%88%AA%E5%B1%8F%E7%9B%91%E5%90%AC%E6%93%8D%E4%BD%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/12/%E8%AF%A6%E7%BB%86%E8%AE%B2%E8%A7%A3%E5%AE%89%E5%8D%93%E6%88%AA%E5%B1%8F%E7%9B%91%E5%90%AC%E6%93%8D%E4%BD%9C/" class="post-title-link" itemprop="url">详细讲解安卓截屏监听操作</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-12 20:03:39" itemprop="dateCreated datePublished" datetime="2017-05-12T20:03:39+08:00">2017-05-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h2><p>项目中有时会遇到监听用户截屏操作的需求，应用场景也比较丰富。</p>
<p>eg. 1: 某个隐私页面禁止截屏，当发现用户截屏后，删除该截屏文件；</p>
<p>eg. 2: 当用户截屏时，可能是需要进行分享，意见反馈等操作，此时进行弹窗提示，方便用户操作（支付宝就有类似功能）。</p>
<h2 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h2><p>安卓系统里面并没有提供监听截屏的接口，所以就需要自己去实现（不然也不会有本文）。</p>
<ul>
<li><p>一般来说，对于某一操作的监听，第一直觉就是监听对应按键的点击事件。但是各种定制系统的截图方式五花八门，对截图按键的监听并不容易。</p>
<blockquote>
<p> 截图方式 ：</p>
<p>eg.1  快捷组合键截屏 ：【电源键】+【音量-】；【home键】+【音量-】；【电源键】+【Home键】……</p>
<p>eg.2 快捷菜单的截屏按键</p>
<p>eg.3 借助其它软件截屏：例如QQ辅助功能中的摇一摇截屏；豌豆荚，360手机助手等通过usb调试的截屏 ……</p>
<p>eg.4 定制系统的其它截屏方式：三指下滑截屏 ；长按指纹键截屏 ……</p>
</blockquote>
<p>综上，此路不通。</p>
</li>
<li><p>既然无法通过按键点击判断出截屏操作，那就只好在生成截屏图片后进行判断。</p>
<p>也就是 <strong>【对图库进行监听】</strong>，如果  <strong>【特定时间】</strong> 增加了  <strong>【符合规则的图片】</strong> ，则判定用户进行了截图操作。</p>
</li>
</ul>
<h2 id="具体操作"><a href="#具体操作" class="headerlink" title="具体操作"></a>具体操作</h2><h3 id="1-权限"><a href="#1-权限" class="headerlink" title="1. 权限"></a>1. 权限</h3><p>因为对图库文件进行监听，需要用到内存读的权限，所以需要在 AndroidManifest.xml 中添加权限:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">&quot;android.permission.READ_EXTERNAL_STORAGE&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p>内存读写权限属于高危权限，在安卓6.0及以上的系统还需要进行动态权限的申请。在对应页面的Activity中进行权限判断以及申请。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (Build.VERSION.SDK_INT &gt; <span class="number">22</span>) &#123;</span><br><span class="line">    List&lt;String&gt; permissionList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="comment">// 检查是否有内存权限</span></span><br><span class="line">    <span class="keyword">if</span> (ContextCompat.checkSelfPermission(ScreenshotsActivity.<span class="keyword">this</span>, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) &#123;</span><br><span class="line">        permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 开始截图监听</span></span><br><span class="line">        doStart();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (permissionList != <span class="keyword">null</span> &amp;&amp; (permissionList.size() != <span class="number">0</span>)) &#123;</span><br><span class="line">        ActivityCompat.requestPermissions(ScreenshotsActivity.<span class="keyword">this</span>, permissionList.toArray(<span class="keyword">new</span> String[permissionList.size()]), <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-创建截图监听器"><a href="#2-创建截图监听器" class="headerlink" title="2. 创建截图监听器"></a>2. 创建截图监听器</h3><p>创建截图监听器文件，当判断用户进行截图操作之后，以接口回调的方式进行处理。</p>
<blockquote>
<p>那么如何判断进行了截图操作呢？这就又回归到分析中的结论：</p>
<p>​    【监听图库】，若 【特定时间内】增加【符合规则的图片】，则判定进行了截图操作。</p>
</blockquote>
<h4 id="2-1-监听图库"><a href="#2-1-监听图库" class="headerlink" title="2.1 监听图库"></a>2.1 监听图库</h4><p>我们要对图库进行监听，需要读取媒体数据库。那么需要监听读取的列如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 读取媒体数据库时需要读取的列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] MEDIA_PROJECTIONS = &#123;</span><br><span class="line">    MediaStore.Images.ImageColumns.DATA,</span><br><span class="line">        MediaStore.Images.ImageColumns.DATE_TAKEN,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 读取媒体数据库时需要读取的列, 其中 WIDTH 和 HEIGHT 字段在 API 16 以后才有</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] MEDIA_PROJECTIONS_API_16 = &#123;</span><br><span class="line">    MediaStore.Images.ImageColumns.DATA,</span><br><span class="line">    MediaStore.Images.ImageColumns.DATE_TAKEN,</span><br><span class="line">    MediaStore.Images.ImageColumns.WIDTH,</span><br><span class="line">    MediaStore.Images.ImageColumns.HEIGHT,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p> 图库监听代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">Cursor cursor = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">// 数据改变时查询数据库中最后加入的一条数据</span></span><br><span class="line">    cursor = mContext.getContentResolver().query(</span><br><span class="line">            contentUri,</span><br><span class="line">            Build.VERSION.SDK_INT &lt; <span class="number">16</span> ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,</span><br><span class="line">            <span class="keyword">null</span>,</span><br><span class="line">            <span class="keyword">null</span>,</span><br><span class="line">            MediaStore.Images.ImageColumns.DATE_ADDED + <span class="string">&quot; desc limit 1&quot;</span></span><br><span class="line">    );</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (cursor == <span class="keyword">null</span>) &#123;</span><br><span class="line">        LogUtils.e(<span class="string">&quot;Deviant logic.&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!cursor.moveToFirst()) &#123;</span><br><span class="line">        LogUtils.e(<span class="string">&quot;Cursor no data.&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取各列的索引</span></span><br><span class="line">    <span class="keyword">int</span> dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);</span><br><span class="line">    <span class="keyword">int</span> dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN);</span><br><span class="line">    <span class="keyword">int</span> widthIndex = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> heightIndex = -<span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= <span class="number">16</span>) &#123;</span><br><span class="line">        widthIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.WIDTH);</span><br><span class="line">        heightIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.HEIGHT);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取行数据</span></span><br><span class="line">    String data = cursor.getString(dataIndex);</span><br><span class="line">    <span class="keyword">long</span> dateTaken = cursor.getLong(dateTakenIndex);</span><br><span class="line">    <span class="keyword">int</span> width = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> height = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (widthIndex &gt;= <span class="number">0</span> &amp;&amp; heightIndex &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">        width = cursor.getInt(widthIndex);</span><br><span class="line">        height = cursor.getInt(heightIndex);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// API 16 之前, 宽高要手动获取</span></span><br><span class="line">        Point size = getImageSize(data);</span><br><span class="line">        width = size.x;</span><br><span class="line">        height = size.y;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 处理获取到的第一行数据</span></span><br><span class="line">    handleMediaRowData(data, dateTaken, width, height);</span><br></pre></td></tr></table></figure>

<h4 id="2-2-特定时间内"><a href="#2-2-特定时间内" class="headerlink" title="2.2 特定时间内"></a>2.2 特定时间内</h4><p>所谓特定时间内，即为监听增加开始和结束的方法。可以通过两个方法进行时间的控制。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 启动监听</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">startListen</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    assertInMainThread();</span><br><span class="line"></span><br><span class="line">    sHasCallbackPaths.clear();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 记录开始监听的时间戳</span></span><br><span class="line">    mStartListenTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建内容观察者</span></span><br><span class="line">    mInternalObserver = <span class="keyword">new</span> MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler);</span><br><span class="line">    mExternalObserver = <span class="keyword">new</span> MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注册内容观察者</span></span><br><span class="line">    mContext.getContentResolver().registerContentObserver(</span><br><span class="line">            MediaStore.Images.Media.INTERNAL_CONTENT_URI,</span><br><span class="line">            <span class="keyword">false</span>,</span><br><span class="line">            mInternalObserver</span><br><span class="line">    );</span><br><span class="line">    mContext.getContentResolver().registerContentObserver(</span><br><span class="line">            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,</span><br><span class="line">            <span class="keyword">false</span>,</span><br><span class="line">            mExternalObserver</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 停止监听</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stopListen</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    assertInMainThread();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注销内容观察者</span></span><br><span class="line">    <span class="keyword">if</span> (mInternalObserver != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          mContext.getContentResolver().unregisterContentObserver(mInternalObserver);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        mInternalObserver = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (mExternalObserver != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          mContext.getContentResolver().unregisterContentObserver(mExternalObserver);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        mExternalObserver = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 清空数据</span></span><br><span class="line">    mStartListenTime = <span class="number">0</span>;</span><br><span class="line">    sHasCallbackPaths.clear();</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="2-3-符合规则的图片"><a href="#2-3-符合规则的图片" class="headerlink" title="2.3 符合规则的图片"></a>2.3 符合规则的图片</h4><p>判断是否符合规则，首先要先定制一个规则。判断截图，一般可以从以下几个方面进行判断：</p>
<ul>
<li><p>时间判断：</p>
<ul>
<li><p>也就是我们2.2中所说的特定时间内，如果图片的创建时间不在其中，则不认定为截图；</p>
</li>
<li><p>为了提高容错性，也可以对时间限制进行适当放松；</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 如果加入数据库的时间在开始监听之前, 或者与当前时间相差大于10秒, 则认为当前没有截屏</span></span><br><span class="line"><span class="keyword">if</span> (dateTaken &lt; mStartListenTime || (System.currentTimeMillis() - dateTaken) &gt; <span class="number">10</span> * <span class="number">1000</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>尺寸判断：</p>
<ul>
<li><p>屏幕是有固定分辨率的，一般来说，屏幕截图的分辨率也应该小于屏幕的分辨率；</p>
</li>
<li><p>但是如果是长截图，则图片的高度会超出屏幕；（是否判断长截图，根据自己需求制定）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 尺寸判断</span></span><br><span class="line"><span class="keyword">if</span> (sScreenRealSize != <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="comment">// 如果图片尺寸超出屏幕, 则认为当前没有截屏（此处没有判断长截屏）</span></span><br><span class="line">    <span class="keyword">if</span> (!((width &lt;= sScreenRealSize.x &amp;&amp; height &lt;= sScreenRealSize.y)</span><br><span class="line">            || (height &lt;= sScreenRealSize.x &amp;&amp; width &lt;= sScreenRealSize.y))) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>路径名称判断</p>
<ul>
<li><p>通过统计来看，截图文件的图片绝大多数的情况下都会包含screenshot或者类似的关键字。我们在这里进行图片路径的判断。</p>
</li>
<li><p>经过整理得出以下关键字，已经涵盖绝大多数情况的系统机型截图：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 此处忽略大小写，后续判断时，统一转换为小写即可</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] KEYWORDS = &#123;</span><br><span class="line">        <span class="string">&quot;screenshot&quot;</span>, <span class="string">&quot;screen_shot&quot;</span>, <span class="string">&quot;screen-shot&quot;</span>, <span class="string">&quot;screen shot&quot;</span>,</span><br><span class="line">        <span class="string">&quot;screencapture&quot;</span>, <span class="string">&quot;screen_capture&quot;</span>, <span class="string">&quot;screen-capture&quot;</span>, <span class="string">&quot;screen capture&quot;</span>,</span><br><span class="line">        <span class="string">&quot;screencap&quot;</span>, <span class="string">&quot;screen_cap&quot;</span>, <span class="string">&quot;screen-cap&quot;</span>, <span class="string">&quot;screen cap&quot;</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></li>
<li><p>判断是否包含关键字</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将路径转换为小写</span></span><br><span class="line">data = data.toLowerCase();</span><br><span class="line"><span class="comment">// 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了</span></span><br><span class="line"><span class="keyword">for</span> (String keyWork : KEYWORDS) &#123;</span><br><span class="line">    <span class="keyword">if</span> (data.contains(keyWork)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<h3 id="3-调用"><a href="#3-调用" class="headerlink" title="3. 调用"></a>3. 调用</h3><p>完成上述操作之后，即可在响应页面开始监听，并进行响应操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">manager = ScreenShotListenManager.newInstance(ScreenshotsActivity.<span class="keyword">this</span>);</span><br><span class="line">manager.setListener(</span><br><span class="line">        <span class="keyword">new</span> ScreenShotListenManager.OnScreenShotListener() &#123;</span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onShot</span><span class="params">(String imagePath)</span> </span>&#123;</span><br><span class="line">                <span class="comment">// do something            </span></span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">);</span><br></pre></td></tr></table></figure>









<h2 id="完整代码："><a href="#完整代码：" class="headerlink" title="完整代码："></a>完整代码：</h2><p>ScreenShotListenManager.java</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 读取媒体数据库时需要读取的列</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] MEDIA_PROJECTIONS = &#123;</span><br><span class="line">        MediaStore.Images.ImageColumns.DATA,</span><br><span class="line">        MediaStore.Images.ImageColumns.DATE_TAKEN,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 读取媒体数据库时需要读取的列, 其中 WIDTH 和 HEIGHT 字段在 API 16 以后才有</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] MEDIA_PROJECTIONS_API_16 = &#123;</span><br><span class="line">        MediaStore.Images.ImageColumns.DATA,</span><br><span class="line">        MediaStore.Images.ImageColumns.DATE_TAKEN,</span><br><span class="line">        MediaStore.Images.ImageColumns.WIDTH,</span><br><span class="line">        MediaStore.Images.ImageColumns.HEIGHT,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 截屏依据中的路径判断关键字</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String[] KEYWORDS = &#123;</span><br><span class="line">        <span class="string">&quot;screenshot&quot;</span>, <span class="string">&quot;screen_shot&quot;</span>, <span class="string">&quot;screen-shot&quot;</span>, <span class="string">&quot;screen shot&quot;</span>,</span><br><span class="line">        <span class="string">&quot;screencapture&quot;</span>, <span class="string">&quot;screen_capture&quot;</span>, <span class="string">&quot;screen-capture&quot;</span>, <span class="string">&quot;screen capture&quot;</span>,</span><br><span class="line">        <span class="string">&quot;screencap&quot;</span>, <span class="string">&quot;screen_cap&quot;</span>, <span class="string">&quot;screen-cap&quot;</span>, <span class="string">&quot;screen cap&quot;</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> Point sScreenRealSize;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 已回调过的路径</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> List&lt;String&gt; sHasCallbackPaths = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> Context mContext;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> OnScreenShotListener mListener;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">long</span> mStartListenTime;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 内部存储器内容观察者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> MediaContentObserver mInternalObserver;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 外部存储器内容观察者</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> MediaContentObserver mExternalObserver;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 运行在 UI 线程的 Handler, 用于运行监听器回调</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> Handler mUiHandler = <span class="keyword">new</span> Handler(Looper.getMainLooper());</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="title">ScreenShotListenManager</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (context == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;The context must not be null.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    mContext = context;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取屏幕真实的分辨率</span></span><br><span class="line">    <span class="keyword">if</span> (sScreenRealSize == <span class="keyword">null</span>) &#123;</span><br><span class="line">        sScreenRealSize = getRealScreenSize();</span><br><span class="line">        <span class="keyword">if</span> (sScreenRealSize != <span class="keyword">null</span>) &#123;</span><br><span class="line">            LogUtils.e(<span class="string">&quot;Screen Real Size: &quot;</span> + sScreenRealSize.x + <span class="string">&quot; * &quot;</span> + sScreenRealSize.y);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            LogUtils.e(<span class="string">&quot;Get screen real size failed.&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ScreenShotListenManager <span class="title">newInstance</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">    assertInMainThread();</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ScreenShotListenManager(context);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 启动监听</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">startListen</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    assertInMainThread();</span><br><span class="line"></span><br><span class="line">    sHasCallbackPaths.clear();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 记录开始监听的时间戳</span></span><br><span class="line">    mStartListenTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建内容观察者</span></span><br><span class="line">    mInternalObserver = <span class="keyword">new</span> MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler);</span><br><span class="line">    mExternalObserver = <span class="keyword">new</span> MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注册内容观察者</span></span><br><span class="line">    mContext.getContentResolver().registerContentObserver(</span><br><span class="line">            MediaStore.Images.Media.INTERNAL_CONTENT_URI,</span><br><span class="line">            <span class="keyword">false</span>,</span><br><span class="line">            mInternalObserver</span><br><span class="line">    );</span><br><span class="line">    mContext.getContentResolver().registerContentObserver(</span><br><span class="line">            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,</span><br><span class="line">            <span class="keyword">false</span>,</span><br><span class="line">            mExternalObserver</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 停止监听</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stopListen</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    assertInMainThread();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注销内容观察者</span></span><br><span class="line">    <span class="keyword">if</span> (mInternalObserver != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          mContext.getContentResolver().unregisterContentObserver(mInternalObserver);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        mInternalObserver = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (mExternalObserver != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          mContext.getContentResolver().unregisterContentObserver(mExternalObserver);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        mExternalObserver = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 清空数据</span></span><br><span class="line">    mStartListenTime = <span class="number">0</span>;</span><br><span class="line">    sHasCallbackPaths.clear();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 处理媒体数据库的内容改变</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handleMediaContentChange</span><span class="params">(Uri contentUri)</span> </span>&#123;</span><br><span class="line">    Cursor cursor = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 数据改变时查询数据库中最后加入的一条数据</span></span><br><span class="line">        cursor = mContext.getContentResolver().query(</span><br><span class="line">                contentUri,</span><br><span class="line">                Build.VERSION.SDK_INT &lt; <span class="number">16</span> ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,</span><br><span class="line">                <span class="keyword">null</span>,</span><br><span class="line">                <span class="keyword">null</span>,</span><br><span class="line">                MediaStore.Images.ImageColumns.DATE_ADDED + <span class="string">&quot; desc limit 1&quot;</span></span><br><span class="line">        );</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (cursor == <span class="keyword">null</span>) &#123;</span><br><span class="line">            LogUtils.e(<span class="string">&quot;Deviant logic.&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (!cursor.moveToFirst()) &#123;</span><br><span class="line">            LogUtils.e(<span class="string">&quot;Cursor no data.&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取各列的索引</span></span><br><span class="line">        <span class="keyword">int</span> dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);</span><br><span class="line">        <span class="keyword">int</span> dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN);</span><br><span class="line">        <span class="keyword">int</span> widthIndex = -<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> heightIndex = -<span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= <span class="number">16</span>) &#123;</span><br><span class="line">            widthIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.WIDTH);</span><br><span class="line">            heightIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.HEIGHT);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取行数据</span></span><br><span class="line">        String data = cursor.getString(dataIndex);</span><br><span class="line">        <span class="keyword">long</span> dateTaken = cursor.getLong(dateTakenIndex);</span><br><span class="line">        <span class="keyword">int</span> width = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> height = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">if</span> (widthIndex &gt;= <span class="number">0</span> &amp;&amp; heightIndex &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">            width = cursor.getInt(widthIndex);</span><br><span class="line">            height = cursor.getInt(heightIndex);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// API 16 之前, 宽高要手动获取</span></span><br><span class="line">            Point size = getImageSize(data);</span><br><span class="line">            width = size.x;</span><br><span class="line">            height = size.y;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 处理获取到的第一行数据</span></span><br><span class="line">        handleMediaRowData(data, dateTaken, width, height);</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (cursor != <span class="keyword">null</span> &amp;&amp; !cursor.isClosed()) &#123;</span><br><span class="line">            cursor.close();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> Point <span class="title">getImageSize</span><span class="params">(String imagePath)</span> </span>&#123;</span><br><span class="line">    BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</span><br><span class="line">    options.inJustDecodeBounds = <span class="keyword">true</span>;</span><br><span class="line">    BitmapFactory.decodeFile(imagePath, options);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Point(options.outWidth, options.outHeight);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 处理获取到的一行数据</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handleMediaRowData</span><span class="params">(String data, <span class="keyword">long</span> dateTaken, <span class="keyword">int</span> width, <span class="keyword">int</span> height)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (checkScreenShot(data, dateTaken, width, height)) &#123;</span><br><span class="line">        LogUtils.e(<span class="string">&quot;ScreenShot: path = &quot;</span> + data + <span class="string">&quot;; size = &quot;</span> + width + <span class="string">&quot; * &quot;</span> + height</span><br><span class="line">                + <span class="string">&quot;; date = &quot;</span> + dateTaken);</span><br><span class="line">        <span class="keyword">if</span> (mListener != <span class="keyword">null</span> &amp;&amp; !checkCallback(data)) &#123;</span><br><span class="line">            mListener.onShot(data);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 如果在观察区间媒体数据库有数据改变，又不符合截屏规则，则输出到 log 待分析</span></span><br><span class="line">        LogUtils.e(<span class="string">&quot;Media content changed, but not screenshot: path = &quot;</span> + data</span><br><span class="line">                + <span class="string">&quot;; size = &quot;</span> + width + <span class="string">&quot; * &quot;</span> + height + <span class="string">&quot;; date = &quot;</span> + dateTaken);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 判断指定的数据行是否符合截屏条件</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">checkScreenShot</span><span class="params">(String data, <span class="keyword">long</span> dateTaken, <span class="keyword">int</span> width, <span class="keyword">int</span> height)</span> </span>&#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * 判断依据一: 时间判断</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="comment">// 如果加入数据库的时间在开始监听之前, 或者与当前时间相差大于10秒, 则认为当前没有截屏</span></span><br><span class="line">    <span class="keyword">if</span> (dateTaken &lt; mStartListenTime || (System.currentTimeMillis() - dateTaken) &gt; <span class="number">10</span> * <span class="number">1000</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * 判断依据二: 尺寸判断</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">if</span> (sScreenRealSize != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 如果图片尺寸超出屏幕, 则认为当前没有截屏</span></span><br><span class="line">        <span class="keyword">if</span> (!((width &lt;= sScreenRealSize.x &amp;&amp; height &lt;= sScreenRealSize.y)</span><br><span class="line">                || (height &lt;= sScreenRealSize.x &amp;&amp; width &lt;= sScreenRealSize.y))) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * 判断依据三: 路径判断</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">if</span> (TextUtils.isEmpty(data)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    data = data.toLowerCase();</span><br><span class="line">    <span class="comment">// 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了</span></span><br><span class="line">    <span class="keyword">for</span> (String keyWork : KEYWORDS) &#123;</span><br><span class="line">        <span class="keyword">if</span> (data.contains(keyWork)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 判断是否已回调过, 某些手机ROM截屏一次会发出多次内容改变的通知; &lt;br/&gt;</span></span><br><span class="line"><span class="comment"> * 删除一个图片也会发通知, 同时防止删除图片时误将上一张符合截屏规则的图片当做是当前截屏.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">checkCallback</span><span class="params">(String imagePath)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (sHasCallbackPaths.contains(imagePath)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 大概缓存15~20条记录便可</span></span><br><span class="line">    <span class="keyword">if</span> (sHasCallbackPaths.size() &gt;= <span class="number">20</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">            sHasCallbackPaths.remove(<span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    sHasCallbackPaths.add(imagePath);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取屏幕分辨率</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> Point <span class="title">getRealScreenSize</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Point screenSize = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        screenSize = <span class="keyword">new</span> Point();</span><br><span class="line">        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);</span><br><span class="line">        Display defaultDisplay = windowManager.getDefaultDisplay();</span><br><span class="line">        <span class="keyword">if</span> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN_MR1) &#123;</span><br><span class="line">            defaultDisplay.getRealSize(screenSize);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Method mGetRawW = Display.class.getMethod(<span class="string">&quot;getRawWidth&quot;</span>);</span><br><span class="line">                Method mGetRawH = Display.class.getMethod(<span class="string">&quot;getRawHeight&quot;</span>);</span><br><span class="line">                screenSize.set(</span><br><span class="line">                        (Integer) mGetRawW.invoke(defaultDisplay),</span><br><span class="line">                        (Integer) mGetRawH.invoke(defaultDisplay)</span><br><span class="line">                );</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> screenSize;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 设置截屏监听器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setListener</span><span class="params">(OnScreenShotListener listener)</span> </span>&#123;</span><br><span class="line">    mListener = listener;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">interface</span> <span class="title">OnScreenShotListener</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onShot</span><span class="params">(String imagePath)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">assertInMainThread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (Looper.myLooper() != Looper.getMainLooper()) &#123;</span><br><span class="line">        StackTraceElement[] elements = Thread.currentThread().getStackTrace();</span><br><span class="line">        String methodMsg = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (elements != <span class="keyword">null</span> &amp;&amp; elements.length &gt;= <span class="number">4</span>) &#123;</span><br><span class="line">            methodMsg = elements[<span class="number">3</span>].toString();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Call the method must be in main thread: &quot;</span> + methodMsg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 媒体内容观察者(观察媒体数据库的改变)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">MediaContentObserver</span> <span class="keyword">extends</span> <span class="title">ContentObserver</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Uri mContentUri;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">MediaContentObserver</span><span class="params">(Uri contentUri, Handler handler)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(handler);</span><br><span class="line">        mContentUri = contentUri;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onChange</span><span class="params">(<span class="keyword">boolean</span> selfChange)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onChange(selfChange);</span><br><span class="line">        handleMediaContentChange(mContentUri);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3、 调用 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">manager = ScreenShotListenManager.newInstance(ScreenshotsActivity.<span class="keyword">this</span>);</span><br><span class="line">manager.setListener(</span><br><span class="line">        <span class="keyword">new</span> ScreenShotListenManager.OnScreenShotListener() &#123;</span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onShot</span><span class="params">(String imagePath)</span> </span>&#123;</span><br><span class="line">                <span class="comment">// do something</span></span><br><span class="line">               </span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">);</span><br></pre></td></tr></table></figure>

<p>参考：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/xietansheng/article/details/52692163">https://blog.csdn.net/xietansheng/article/details/52692163</a> </p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2017/05/11/%E8%BF%9C%E7%A8%8B%E8%BF%9E%E6%8E%A5mysql%E6%95%B0%E6%8D%AE%E5%BA%93/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2017/05/11/%E8%BF%9C%E7%A8%8B%E8%BF%9E%E6%8E%A5mysql%E6%95%B0%E6%8D%AE%E5%BA%93/" class="post-title-link" itemprop="url">远程连接MySQL数据库</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-05-11 10:54:09" itemprop="dateCreated datePublished" datetime="2017-05-11T10:54:09+08:00">2017-05-11</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-25 22:37:20" itemprop="dateModified" datetime="2021-08-25T22:37:20+08:00">2021-08-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MySQL/" itemprop="url" rel="index"><span itemprop="name">MySQL</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <blockquote>
<p>默认情况下，MySQL帐号不允许从远程登陆，只能在localhost登录。所以得通过修改MySQL数据库中的user表来更改。本文提供两种方法，第一种是网上搜到的，第二种是我自己琢磨的……亲测有效。适合像我这样的小白。</p>
</blockquote>
<p>##控制台命令</p>
<p>1、在控制台执行 mysql -u root -p mysql，系统提示输入数据库root用户的密码，输入完成后即进入mysql控制台，这个命令的第一个mysql是执行命令，第二个mysql是系统数据名称，不一样的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql -u root -p mysql</span><br></pre></td></tr></table></figure>

<p>2、use命令可以让我们来使用数据库，这里选择mysql数据库。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">use mysql</span><br></pre></td></tr></table></figure>

<p>3、恩……先看下用户表里的内容。（要是不想看的话，此步可以略去，没啥影响）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT User ,Password, Host FROM user;</span><br></pre></td></tr></table></figure>


<p>4、接下来就要用到GRANT语句了，不会不要紧。举个例子你就明白了。</p>
<p>例1：添加一个新的 root 用户, 密码为空, 只允许 192.168.1.100 连接：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GRANT ALL PRIVILEGES ON *.* TO &#x27;root&#x27;@&#x27;192.168.1.100&#x27; IDENTIFIED BY &#x27;&#x27; WITH GRANT OPTION;</span><br></pre></td></tr></table></figure>
<p>例2：添加一个新的 suker用户, 密码为WeiChao, 允许所有的连接</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GRANT ALL PRIVILEGES ON *.* TO ‘suker&#x27;@&#x27;%&#x27; IDENTIFIED BY ‘WeiChao&#x27; WITH GRANT OPTION;  </span><br></pre></td></tr></table></figure>

<blockquote>
<p>例子可以这样理解: suker是用户名，%是主机名（%代表任意主机），这里你也可替换成任意其它用户名或指定唯一的IP地址；’WeiChao’是给授权用户指定的登录数据库的密码；另外需要说明一点的是我这里的都是授权所有权限，可以指定部分权限，GRANT具体操作详情见：<a target="_blank" rel="noopener" href="http://dev.mysql.com/doc/refman/5.1/en/grant.html">http://dev.mysql.com/doc/refman/5.1/en/grant.html</a></p>
</blockquote>
<p>5、不放心的话可以在mysql控制台执行 select host, user from user; 检查一下用户表里的内容。</p>
<h2 id="数据库管理器软件"><a href="#数据库管理器软件" class="headerlink" title="数据库管理器软件"></a>数据库管理器软件</h2><blockquote>
<p>这个方法说起来有点投机取巧，因为我服务器上装的是windows server2012，而且装了个Navicat Premium——一个很值得推荐的数据库管理工具，能连接多种数据库。当然，别的数据库管理软件也可以。</p>
</blockquote>
<p>1.先新建连接，通过localhost连接上数据库。</p>
<p>2.选中该连接后，点击用户–&gt;新建用户<br><img src="http://img.blog.csdn.net/20170511130235301" alt="点击新建用户"></p>
<p>3.在新标签页中，设置用户名，主机名，密码，权限等等。我觉得最大 的好处就是省去GRANT操作，简洁明了，可视化操作，可以设置的选项很多，比如最多连接数目，每小时最多查询次数啊一类的。包括权限也可以轻松设置。<br><img src="http://img.blog.csdn.net/20170511130822945" alt="设置基本信息"><br><img src="http://img.blog.csdn.net/20170511131556087" alt="设置权限"></p>
<p>4.重启一下mysql服务，使操作生效 。</p>
<blockquote>
<p>也可以选择mysql数据库的user表。直接修改表中的数据来设置。</p>
</blockquote>
<blockquote>
<p><img src="http://img.blog.csdn.net/20170511132337796" alt="修改user表数据"></p>
</blockquote>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/4/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/4/">4</a><span class="page-number current">5</span>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">vchao</p>
  <div class="site-description" itemprop="description">怀揣好奇，梦想改变世界的菜鸟极客</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">46</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备 17022751号-1 </a>
      <img src="https://beian.miit.gov.cn" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vchao</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
